# rePython - Python RPC server/client library
#
# Copyright (C) 2013 Andrew Dunai, andunai@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import socket
import netpoll
from threading import Thread
import inspect
import struct
import serializer
import errors
import security
import env
import util

env.loadEnv(globals(),
	('REPYTHON_PORT', env.UNSIGNED, 9999),
	('REPYTHON_TIMEOUT', env.UNSIGNED, 5)
)
class Client:#(Thread):
	def __init__(self, host = '127.0.0.1', useEncryption = False):
#		Thread.__init__(self)
		self.terminated = False
		self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#		self.client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#		self.client.bind(('',PORT))
		self.client.connect((host,REPYTHON_PORT))
		self.rsaPool = security.RSAPool()

		#netpoll.send(self.client, serializer.serializeCall('default', 'announceEncryption', self.rsaPool.getMyPublic(), {}, None))
		if useEncryption:
			RemoteMethod(self, 'default', 'announceEncryption')(*self.rsaPool.getMyPublic())

#		self.server.listen(5)
#		self.methods = []
#		self.daemon = True
#		self.start()

#	def run(self):
#		while not self.terminated:
#			sock, info = self.server.accept()
#			RequestProcessor(sock, info)
#		pass

#	def provide(self, method, namespace='default'):
#		if not hasattr(method, '__call__'):
#			raise NotCallableException('Object %s is not callable, thus cannot be provided' % method.__name__)
#		methodName = method.__name__
#		methodArgs = method.func_code.co_varnames
#		self.methods.append((methodName, methodArgs))

#	def call(self, namespace, method):
#		return 

	def __getattr__(self, namespace):
		return Namespace(self, namespace)

class Namespace:
	def __init__(self, client, namespace):
		self.client = client
		self.namespace = namespace

	def __getattr__(self, method):
		return RemoteMethod(self.client, self.namespace, method)

class RemoteMethod:
	def __init__(self, client, namespace, method):
		self.client = client
		self.namespace = namespace
		self.method = method

	def __call__(self, *kargs, **kwargs):
		util.log.debug('Calling %s' % self.method)
		util.log.debug('  from namespace %s' % self.namespace)
		util.log.debug('    kargs  : %s' % str(kargs))
		util.log.debug('    kwargs : %s' % str(kwargs))
		try:
			netpoll.send(self.client.client, serializer.serializeCall(self.namespace, self.method, kargs, kwargs, self.client.rsaPool))
		except socket.error, e:
			raise errors.RPCSocketError()

		lenData = netpoll.recv(self.client.client, 4, REPYTHON_TIMEOUT)
		if not lenData:
			raise errors.RPCTimeout()
		res = struct.unpack('<i', lenData)
		if not res:
			raise errors.RPCTimeout()
		length = res[0]
		responseData = serializer.unSerialize(netpoll.recv(self.client.client, length, REPYTHON_TIMEOUT), self.client.rsaPool)
		util.log.debug('Got result: exceptionValue: %s, publicKey: %s, returnValue: %s' % (responseData['exceptionValue'] is not None, responseData['returnValue'] is not None, responseData['publicKey'] is not None))
		if responseData['exceptionValue']:
			raise responseData['exceptionValue']
		elif responseData['publicKey']:
			util.log.debug('Received server public key')
			self.client.rsaPool.setTheirPublic(*responseData['publicKey'])
		else:
			return responseData['returnValue']
